package com.nai365.nart.search.service.impl;

import cn.hutool.core.lang.Console;
import cn.hutool.json.JSONUtil;
import com.nai365.nart.common.core.es.SkuEsModel;
import com.nai365.nart.common.core.es.SpuEsModel;
import com.nai365.nart.search.config.NartElasticSearchConfig;
import com.nai365.nart.search.constant.EsConstant;
import com.nai365.nart.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Created: with IntelliJ IDEA.
 * @author: baogs
 * @createTime: 2021-03-06 16:54
 **/

@Slf4j
@Service("productSaveService")
public class ProductSaveServiceImpl implements ProductSaveService {

    @Autowired
    private RestHighLevelClient esRestClient;

    @Override
    public boolean productStatusUp(List<SpuEsModel> spuEsModels) throws IOException {

//1.在es中建立索引，建立号映射关系（doc/json/product-mapping.json）

        //2. 在ES中保存这些数据
        BulkRequest bulkRequest = new BulkRequest();
        for (SpuEsModel spuEsModel : spuEsModels) {
            //构造保存请求
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(spuEsModel.getId().toString());
//            String jsonString = new Gson().toJson(spuEsModel);
			String jsonString  = JSONUtil.toJsonStr(spuEsModel);
			Console.log("####"+jsonString);
            indexRequest.source(jsonString, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }

        BulkResponse bulk = esRestClient.bulk(bulkRequest, NartElasticSearchConfig.COMMON_OPTIONS);

        //TODO 如果批量错误
        boolean hasFailures = bulk.hasFailures();

        List<String> collect = Arrays.asList(bulk.getItems()).stream().map(item -> {
            return item.getId();
        }).collect(Collectors.toList());

        log.info("商品上架完成：{}",collect);

        return hasFailures;
    }
    @Override
    public boolean productSkuUp(List<SkuEsModel> spuEsModels) throws IOException {

//1.在es中建立索引，建立号映射关系（doc/json/product-mapping.json）

        //2. 在ES中保存这些数据
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel : spuEsModels) {
            //构造保存请求
            IndexRequest indexRequest = new IndexRequest(EsConstant.SKU_INDEX);
            indexRequest.id(skuEsModel.getSkuId().toString());
//            String jsonString = new Gson().toJson(skuEsModel);
			String jsonString  = JSONUtil.toJsonStr(skuEsModel);
            indexRequest.source(jsonString, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }

        BulkResponse bulk = esRestClient.bulk(bulkRequest, NartElasticSearchConfig.COMMON_OPTIONS);

        //TODO 如果批量错误
        boolean hasFailures = bulk.hasFailures();

        List<String> collect = Arrays.asList(bulk.getItems()).stream().map(item -> {
            return item.getId();
        }).collect(Collectors.toList());

        log.info("商品上架完成：{}",collect);

        return hasFailures;
    }


    @Override
	public Long downProduct(Long spuId) {
		long deleted = 0;
		//设置删除条件spuId
		TermQueryBuilder spuIdWhere = QueryBuilders.termQuery("id", spuId);

		//设置删除条件体重根据范围
//		RangeQueryBuilder weightRangeWhere = QueryBuilders.rangeQuery("weight");
//		weightRangeWhere.gte(10);
//		weightRangeWhere.lte(100);
//
//		//设置删除条件模糊匹配名字中带t的记录
//		WildcardQueryBuilder userNameWildCardWhere = QueryBuilders.wildcardQuery("userName.keyword",  "*r*");

		//装载条件并设置must == and  should == or  and、or根据业务需要自行调整
		BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
		queryBuilder.must(spuIdWhere);
//		queryBuilder.should(weightRangeWhere);
//		queryBuilder.should(userNameWildCardWhere);

		DeleteByQueryRequest deleteByQueryRequest = new DeleteByQueryRequest();//构建删除请求
		deleteByQueryRequest.setQuery(queryBuilder);//装载删除条件
		deleteByQueryRequest.indices(EsConstant.PRODUCT_INDEX);//指定删除索引

		try {
			BulkByScrollResponse bulkByScrollResponse = esRestClient.deleteByQuery(deleteByQueryRequest, RequestOptions.DEFAULT);
			deleted = bulkByScrollResponse.getDeleted();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return deleted;

	}
    @Override
	public Long downSku(Long skuId) {
		long deleted = 0;
		//设置删除条件spuId
		TermQueryBuilder spuIdWhere = QueryBuilders.termQuery("skuId", skuId);

		//设置删除条件体重根据范围
//		RangeQueryBuilder weightRangeWhere = QueryBuilders.rangeQuery("weight");
//		weightRangeWhere.gte(10);
//		weightRangeWhere.lte(100);
//
//		//设置删除条件模糊匹配名字中带t的记录
//		WildcardQueryBuilder userNameWildCardWhere = QueryBuilders.wildcardQuery("userName.keyword",  "*r*");

		//装载条件并设置must == and  should == or  and、or根据业务需要自行调整
		BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
		queryBuilder.must(spuIdWhere);
//		queryBuilder.should(weightRangeWhere);
//		queryBuilder.should(userNameWildCardWhere);

		DeleteByQueryRequest deleteByQueryRequest = new DeleteByQueryRequest();//构建删除请求
		deleteByQueryRequest.setQuery(queryBuilder);//装载删除条件
		deleteByQueryRequest.indices(EsConstant.SKU_INDEX);//指定删除索引

		try {
			BulkByScrollResponse bulkByScrollResponse = esRestClient.deleteByQuery(deleteByQueryRequest, RequestOptions.DEFAULT);
			deleted = bulkByScrollResponse.getDeleted();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return deleted;

	}
}
